const Router = require('@koa/router')

const { query } = require('../../utils/async-db')
async function selectAllData() {
  // let sql = 'SELECT * FROM users' // 'SELECT * FROM user where id=?', [1]
  let sql = 'SELECT * FROM users WHERE id=?'
  let dataList = await query( sql, [1] )
  return dataList
}

const users = new Router(
  // {
  //   prefix: 'abc' // 前缀
  // }
)

function getData(ctx) {
  return new Promise((resolve, reject) => {
    let data = ''
    ctx.req.on('data', (chunk) => {
      data+=chunk
      console.log(data)
    })
    ctx.req.on('end', () => {
      console.log(data)
      resolve(data)
      // ctx.body = data
    })
  })
}

// 将POST请求参数字符串解析成JSON
function parseQueryStr( queryStr ) {
  let queryData = {}
  let queryStrList = queryStr.split('&')
  console.log( queryStrList )
  for (  let [ index, queryStr ] of queryStrList.entries()  ) {
    let itemList = queryStr.split('=')
    queryData[ itemList[0] ] = decodeURIComponent(itemList[1])
  }
  return queryData
}

users.post('/signin', async (ctx, next) => {
  console.log(URLSearchParams, 'URLSearchParams')
  let result = await getData(ctx)
  let param = new URLSearchParams(result)
  console.log(param.get('username'))
  ctx.body = parseQueryStr(result)
})

users.get('/list', async (ctx, next) => {
  // let query = ctx.request.query
  // let querystring = ctx.request.querystring
  // ctx.body = querystring
  ctx.session.username = 'abc'
  let dataList = await selectAllData()
  await ctx.render('succ.ejs', {
    data: JSON.stringify(dataList)
  }) 
})

users.post('/signup', async (ctx, next) => {
  const body = ctx.request.body

  let result = await query('insert into users set ?', body)

  ctx.session = body
  // {
  //   user_id: Math.random().toString(36).substr(2),
  //   count: 0
  // }

  await ctx.render('succ.ejs', {
    data: JSON.stringify(result)
  }) 
})

module.exports = users
